from typing import Annotated, List, Optional

from fastapi import APIRouter, Body, Depends, Path, Query, Request

from app.api.deps import CurrentUserDep, DeptServiceDep, require_permission
from app.core import settings
from app.enums.log_module import LogModuleEnum
from app.exceptions.base import AppException
from app.models.system import SysUser
from app.schemas.base import Response
from app.schemas.dept import DeptForm, DeptQuery, DeptVO
from app.schemas.option import IntOption
from app.utils.log_api_call import log

router = APIRouter(prefix=f"{settings.API_V1_STR}/dept", tags=["05.部门接口"])


@router.get(
    "",
    response_model=Response[List[DeptVO]],
    response_model_exclude_none=True,
    summary="部门列表",
    description="查询部门树形列表（支持条件过滤）",
)
@log(content="查询部门列表", module=LogModuleEnum.DEPT.label)
async def get_dept_list(
    request: Request,
    current_user: CurrentUserDep,
    dept_service: DeptServiceDep,
    page_num: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页记录数"),
    keywords: Optional[str] = Query(default=None, description="关键字(部门名称)"),
    status: Optional[int] = Query(default=None, description="状态(1->正常；0->禁用)"),
) -> Response[List[DeptVO]]:
    """
    部门列表
    """
    try:
        query_params = DeptQuery(page_num=page_num, page_size=page_size, keywords=keywords, status=status)
        rs = await dept_service.get_dept_list(query_params)
        return Response(data=rs)
    except Exception as e:
        raise AppException(message="获取部门列表失败") from e


@router.get(
    "/options",
    response_model=Response[List[IntOption]],
    response_model_exclude_none=True,
    summary="部门下拉列表",
    description="获取所有部门的下拉选项列表",
)
async def get_dept_options(
    current_user: CurrentUserDep,
    dept_service: DeptServiceDep,
) -> Response[List[IntOption]]:
    """
    部门下拉列表
    """
    try:
        rs = await dept_service.get_dept_options()
        return Response(data=rs)
    except Exception as e:
        raise AppException(message="获取部门下拉列表失败") from e


@router.post("", response_model=Response[int], summary="新增部门", description="创建新部门，需 sys:dept:add 权限")
@log(content="新增部门", module=LogModuleEnum.DEPT.label)
async def save_dept(
    request: Request,
    dept_service: DeptServiceDep,
    current_user: Annotated[SysUser, Depends(require_permission("sys:dept:add"))],
    form_data: DeptForm = Body(..., description="部门表单数据"),
) -> Response[int]:
    """
    新增部门
    """
    try:
        form_data.op_id = current_user.id
        dept = await dept_service.save_dept(form_data)
        return Response.success(data=dept.id)
    except Exception as e:
        raise AppException(message="新增部门失败") from e


@router.get(
    "/{deptId}/form",
    response_model=Response[DeptForm],
    summary="获取部门表单数据",
    description="根据部门ID获取编辑表单数据",
)
async def get_dept_form(
    dept_service: DeptServiceDep,
    current_user: CurrentUserDep,
    deptId: int = Path(..., description="部门ID"),
) -> Response[DeptForm]:
    """
    获取部门表单数据
    """
    try:
        dept = await dept_service.get_dept_byid(deptId)
        print(dept.model_dump_json(indent=2))
        return Response.success(data=DeptForm.model_validate(dept))
    except Exception as e:
        raise AppException(message="获取部门表单数据失败") from e


@router.put(
    "/{deptId}", response_model=Response[int], summary="修改部门", description="更新部门信息，需 sys:dept:edit 权限"
)
@log(content="修改部门", module=LogModuleEnum.DEPT.label)
async def update_dept(
    request: Request,
    dept_service: DeptServiceDep,
    current_user: Annotated[SysUser, Depends(require_permission("sys:dept:edit"))],
    deptId: int = Path(..., description="部门ID"),
    form_data: DeptForm = Body(..., description="部门表单数据"),
) -> Response[int]:
    """
    修改部门
    """
    try:
        form_data.op_id = current_user.id
        form_data.id = deptId
        dept = await dept_service.update_dept(form_data)
        return Response.success(data=dept.id)
    except Exception as e:
        raise AppException(message="修改部门失败") from e


@router.delete(
    "/{ids}",
    response_model=Response[None],
    summary="删除部门",
    description="批量删除部门，多个ID用英文逗号分隔，需 sys:dept:delete 权限",
)
@log(content="删除部门", module=LogModuleEnum.DEPT.label)
async def delete_departments(
    request: Request,
    dept_service: DeptServiceDep,
    ids: Annotated[str, Path(..., description="部门ID，多个以英文逗号(,)分割")],
    current_user: Annotated[SysUser, Depends(require_permission("sys:dept:delete"))],
) -> Response[None]:
    """
    删除部门
    """
    try:
        dept_ids = [int(id) for id in ids.split(",")]
        await dept_service.delete_depts(dept_ids, current_user.id)
        return Response.success()
    except Exception as e:
        raise AppException(message="删除部门失败") from e
